import 'package:flutter/material.dart';
import 'package:zhibao_flutter/api/mine/mine_entity.dart';
import 'package:zhibao_flutter/api/mine/mine_view_model.dart';
import 'package:zhibao_flutter/api/user/user_view_model.dart';
import 'package:zhibao_flutter/util/check/check.dart';
import 'package:zhibao_flutter/util/config/config_route.dart';
import 'package:zhibao_flutter/util/data/q1_data.dart';
import 'package:zhibao_flutter/util/event_bus/avatar_refresh_event.dart';
import 'package:zhibao_flutter/util/func/log.dart';
import 'package:zhibao_flutter/util/ui/ui.dart';
import 'package:zhibao_flutter/widget/appbar/commom_bar.dart';
import 'package:zhibao_flutter/widget/base/my_scaffold.dart';
import 'package:zhibao_flutter/widget/dialog/select_weight_dialog.dart';
import 'package:zhibao_flutter/widget/image/sw_avatar.dart';
import 'package:zhibao_flutter/zone.dart';
import 'package:get/get.dart';
import 'package:zhibao_flutter/api/mine/mine_view_model.dart';
import 'package:zhibao_flutter/dialog/select_picture_dialog.dart';
import 'package:zhibao_flutter/zone.dart';

class ChangeInfoPage extends StatefulWidget {
  const ChangeInfoPage({Key? key}) : super(key: key);

  @override
  State<ChangeInfoPage> createState() => _ChangeInfoPageState();
}

class _ChangeInfoPageState extends State<ChangeInfoPage> {
  bool avatarChange = false;
  RxString nickName = (Q1Data.userInfoEntity?.name ?? '').obs;
  RxString icon = Q1Data.avatar.obs;

  @override
  void initState() {
    super.initState();
    initData();
  }

  Future initData() async {}

  /// 只有照片新上传时才调用
  Future userIndex() async {
    // final selfInfoValue = await mineViewModel.userIndex(null);
    // if (selfInfoValue.data == null) {
    //   return;
    // }
    // Q1Data.userInfoEntity = selfInfoValue.data;
    // LogUtil.d("轮播图长度:::${Q1Data.selfInfoRspEntity?.bannerData?.length}");
  }

  Future uploadAvatar() async {
    selectPictureDialog(
      context,
      callback: (_value) {
        if (!listNoEmpty(_value)) {
          return;
        }
        icon.value = _value.first.resultUrl;

        // If change the avatar and [needShowMindForChangeAvatar] is ture
        // then set [needShowMindForChangeAvatar] as false.
        //
        // [Jul 1]
        // Need change it after commit
        // Here only mark from the current page.
        avatarChange = true;
      },
      isIdFileName: false,
      isCrop: true,
      // 1图片2视频3女性认证图片
      type: 1,
      dir: 'full_info',
      // 如为图片，传整数0或1，0普通1阅后即焚；如为视频，传整数价格
      description: '0',
      showLoading: true,
    );
  }

  Future commit() async {
    final value = await mineViewModel.setSelfInfo(
      context,
      username: nickName.value,
    );
    if (value.data == null) {
      return;
    }

    final valueOfApi =
        await mineViewModel.getSelfInfo(null, Q1Data.loginRspEntity!.token!);
    if (valueOfApi.data == null) {
      return;
    }
    Get.back(result: 1);
    avatarRefreshBus.fire(AvatarRefreshModel());
  }

  @override
  Widget build(BuildContext context) {
    return MyScaffold(
      backgroundColor: Colors.white,
      appBar: CommomBar(
        title: "editInfo".tr,
        rightDMActions: [
          TextButton(
            onPressed: () {
              commit();
            },
            child: Text(
              'save'.tr,
              style: TextStyle(
                // color: !listNoEmpty()
                //     ? Color(0xffB9B9B9)
                //     :
                color: Color(0xff181716),
                fontSize: 16.px,
                fontWeight: FontWeight.w600,
              ),
            ),
          ),
        ],
      ),
      body: ListView(
        padding: EdgeInsets.symmetric(vertical: 15),
        children: [
          Space(height: 9),
          TileShow("basicInfo".tr),
          Obx(
            () => EditInfoItem(
              'avatar'.tr,
              icon.value,
              onTap: () {
                uploadAvatar();
              },
              isAvatar: true,
              errorFieldList: [].obs,
            ),
          ),
          Obx(
            () => EditInfoItem(
              'nickname'.tr,
              nickName.value,
              onTap: () async {
                final value = await Get.toNamed(RouteConfig.modifyNickNamePage,
                    arguments: {'nickName': nickName.value});
                if (!strNoEmpty(value)) return;
                if (nickName.value == value) return;
                nickName.value = value;
              },
              errorFieldList: [].obs,
            ),
          ),
          Space(),
        ],
      ),
    );
  }
}

class TileShow extends StatelessWidget {
  final String title;

  const TileShow(this.title, {Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: EdgeInsets.symmetric(vertical: 6, horizontal: 15),
      child: Row(
        children: [
          Text(
            title,
            style: TextStyle(
              color: Color(0xff181716),
              fontWeight: FontWeight.w600,
            ),
          ),
          Space(width: 2),
        ],
      ),
    );
  }
}

class EditInfoItem extends StatelessWidget {
  final String label;
  final String value;
  final GestureTapCallback onTap;
  final bool isAvatar;
  final RxList errorFieldList;

  EditInfoItem(
    this.label,
    this.value, {
    required this.onTap,
    this.isAvatar = false,
    required this.errorFieldList,
  });

  @override
  Widget build(BuildContext context) {
    return InkWell(
      child: Container(
        height: isAvatar ? 50 : null,
        color: null,
        padding:
            EdgeInsets.symmetric(vertical: isAvatar ? 0 : 15, horizontal: 15),
        child: Row(
          children: [
            Text(
              label,
              style: TextStyle(color: Color(0xff30302F), fontSize: 15),
            ),
            Expanded(
              child: isAvatar
                  ? Container()
                  : Row(
                      mainAxisAlignment: MainAxisAlignment.end,
                      children: [
                        Text(
                          value.length > 15
                              ? value.substring(0, 15) + "..."
                              : value,
                          style:
                              TextStyle(color: Color(0xff828282), fontSize: 13),
                          textAlign: TextAlign.right,
                          maxLines: 1,
                          overflow: TextOverflow.ellipsis,
                        ),
                      ],
                    ),
            ),
            if (isAvatar) SwAvatar(value, size: 33),
            Space(width: 8),
            Image.asset(
              "assets/images/ic_me_arrow_n.png",
              width: 8,
            ),
          ],
        ),
      ),
      onTap: () {
        onTap();
      },
    );
  }
}
